編輯 app\reviews\stardew-valley\page.jsx 檔案內容如下:
import { readFile } from "node:fs/promises"
import { marked } from "marked"
import matter from "gray-matter"
import Heading from "@/components/Heading"
async function getReview() {
// 讀取markdown 文件
const text = await readFile("./content/reviews/stardew-valley.md", "utf8")
// console.log("text =", text)
const { content, data: { title, image, date } } = matter(text)
// md檔轉換成html格式
const body = marked(content)
// console.log("html = ", html)
return { text, date, image, body }
}
async function StardewValleyPage() {
const review = await getReview()
return (
<div>
<Heading>{review.title}</Heading>
<p className="italic py-2">{review.date}</p>
<img src={review.image} alt="" width="640" height="360"
className="mb-2 rounded" />
<article dangerouslySetInnerHTML={{ __html: review.body }} className="prose max-w-screen-sm" />
</div>
)
}
export default StardewValleyPage
加入 slug
import { readFile } from "node:fs/promises"
import { marked } from "marked"
import matter from "gray-matter"
import Heading from "@/components/Heading"
async function getReview(slug) {
// 讀取markdown 文件
const text = await readFile(`./content/reviews/${slug}.md`, "utf8")
// console.log("text =", text)
const { content, data: { title, image, date } } = matter(text)
// md檔轉換成html格式
const body = marked(content)
// console.log("html = ", html)
return { text, date, image, body }
}
async function StardewValleyPage() {
const review = await getReview("stardew-valley")
return (
<div>
<Heading>{review.title}</Heading>
<p className="italic py-2">{review.date}</p>
<img src={review.image} alt="" width="640" height="360"
className="mb-2 rounded" />
<article dangerouslySetInnerHTML={{ __html: review.body }} className="prose max-w-screen-sm" />
</div>
)
}
export default StardewValleyPage
把 getReview 獨立到 lib資料夾下
import { readFile } from "node:fs/promises";
import { marked } from "marked";
import matter from "gray-matter";
export async function getReview(slug) {
// 讀取markdown 文件
const text = await readFile(`./content/reviews/${slug}.md`, "utf8");
// console.log("text =", text)
const {
content,
data: { title, image, date },
} = matter(text);
// md檔轉換成html格式
const body = marked(content);
// console.log("html = ", html)
return { text, date, image, body };
}
引用
import { getReview } from "@/lib/reviews"
import Heading from "@/components/Heading"
async function StardewValleyPage() {
const review = await getReview("stardew-valley")
return (
<div>
<Heading>{review.title}</Heading>
<p className="italic py-2">{review.date}</p>
<img src={review.image} alt="" width="640" height="360"
className="mb-2 rounded" />
<article dangerouslySetInnerHTML={{ __html: review.body }} className="prose max-w-screen-sm" />
</div>
)
}
export default StardewValleyPage
回傳的內容
app\reviews\page.jsx
console.log("[ReviewsPage] reviews:", reviews)
內容如下:
{
slug: 'stardew-valley',
title: 'Stardew Valley',
date: '2023-09-12',
image: '/images/stardew-valley.jpg',
body: '內容太長省略'
}
]
大叔的鐵人賽第十四天結束 :)